""" 不需要去重，遍历套内部双指针
    一直写不出怎么记录总和 """
from typing import *
def threeSumClosest(nums: List[int], target: int) -> int:
    
    nums = sorted(nums)
    res = sum(nums[0:3])
    for i in range(len(nums)):
        l, r = i+1, len(nums) - 1
        while l < r:
            total = nums[i] + nums[l] + nums[r]
            if total < target:
                l += 1
            elif total > target:
                r -= 1
            elif total == target:
                return total

            if abs(res-target) > abs(total-target):
                res = total
    return res
        
print(threeSumClosest([-1,2,1,-4],1))